foreach graph in spearman regression {
use entropy_bible_validation_X, clear

drop if i>1000000
sort i

if "`graph'"=="spearman" {
	local ytitle "r{subscript:s}" 
foreach type in order structure {
	by i: egen rank_`type'=rank(D_`type')
	by i: egen mean_`type'=mean(rank_`type')
	gen dev_`type'=(rank_`type'-mean_`type')^2
	by i: egen sum_`type'=sum(dev_`type')
}

gen cov=(rank_order-mean_order)*(rank_structure-mean_structure)
by i: egen sum_cov=sum(cov)

}
else {
	local ytitle "R{superscript:2}"
replace D_order=1/D_order 

foreach type in order structure {
	by i: egen mean_`type'=mean(D_`type')
	gen dev_`type'=(D_`type'-mean_`type')^2
	by i: egen sum_`type'=sum(dev_`type')
}
gen cov=(D_order-mean_order)*(D_structure-mean_structure)
by i: egen sum_cov=sum(cov)
}
gen correlation=sum_cov/sqrt(sum_order*sum_structure)
 if "`graph'"=="regression" {
 	replace correlation=correlation^2
}

collapse correlation, by(i)

line correlation i,sort nodraw saving(`graph', replace) ///
graphregion(color(white)) scheme(s2mono) ytitle("`ytitle'") yscale(nofextend) xscale(nofextend) ///
xtitle("c") 
}

graph combine spearman.gph regression.gph, cols(1) ///
graphregion(color(white)) scheme(s2mono) xcommon nodraw saving(2.gph, replace)

use entropy_bible_validation_VI, clear
merge m:1 trans using data_bible_final, keep(3)


spearman D_order D_structure
local rho: di %3.2f r(rho)
gen reciprocal=1/D_order

*scatter D_structure rec

reg D_structure rec
predict pred_reg
local r2_1: di %3.2f (e(r2))
mat define mat=e(b)
local b0: di %3.2f mat[1,2]
local b1: di %3.2f mat[1,1]
local N: di %5.0fc e(N)


tw (scatter D_structure D_order, msymbol(Oh) msize(small) mcolor(gs8)) ///
 (line pred_reg D_order, lpattern(dash) lcolor(black) lwidth(medium) sort) /// 
 , legend(position(7) symxsize(2) keygap(0) region(lcolor(white))  cols(1) order(1 2) label(2 "E(D{subscript:s}|D{subscript:o}) = `b0'+`b1'*D{subscript:o}{superscript:-1}; R{superscript:2}=`r2_1'")  ///
 label(1 "r{subscript:s}= `rho' | N = `N'")) ///
 graphregion(color(white)) aspectratio(1)  ///
 ylabel(minmax,format(%3.2f) nogrid) xlabel(minmax,format(%3.2f) nogrid)    ///
 title("New Testament (aggregated)",) 	nodraw saving(1.gph, replace) ytitle("Word structure information") xtitle("Word order information") yscale(nofextend) xscale(nofextend) 

graph combine 1.gph 2.gph, cols(2) ///
graphregion(color(white)) scheme(s2mono) 
graph export fig6.png, height(10000) replace
exit
